package com.nearby.demand.ui;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.auto.layout.lib.AutoLayoutActivity;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.nearby.demand.R;
import com.nearby.demand.db.DaoMaster;
import com.nearby.demand.db.DaoSession;
import com.nearby.demand.db.Demand;
import com.nearby.demand.db.DemandDao;
import com.nearby.demand.presenter.SplashPersenter;
import com.nearby.demand.presenter.SplashPersenterImpl;
import com.nearby.demand.ui.view.SplashView;
import com.nearby.demand.utils.KLog;
import com.nearby.demand.utils.SPUtil;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by IME on 2016/home_1/10.
 */
public class UiSplash extends AutoLayoutActivity implements SplashView {

    @Bind(R.id.ib_show)
    ImageView ibShow;
    @Bind(R.id.tv_code)
    TextView tvCode;
    private SplashPersenter persenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_splash);
        ButterKnife.bind(this);
        initIntent();
    }

    DaoMaster.DevOpenHelper helper;
    DaoMaster master;
    DaoSession session;
    DemandDao dao;
    SQLiteDatabase db;
    Cursor cursor;

    public void initTestDb() {
        helper = new DaoMaster.DevOpenHelper(this, "demand-db", null);
        db = helper.getWritableDatabase();
        master = new DaoMaster(db);
        session = master.newSession();
        dao = session.getDemandDao();
        String id[] = new String[]{
                "as", "as1", "as2", "as3", "as4", "as5", "as6", "as7", "as8", "as9"
        };
        for (int i = 0; i < 10; i++) {
            Demand demand = new Demand(
                    id[i] + " 用户发的一条健身需求，有一起去的吗?",
                    R.drawable.ic_logo_karumi + "",
                    "2015-01-16  2015-01-20",
                    "深圳",
                    "home_3",
                    "健身" + i,id[i]+"");
            dao.insertInTx(demand);
        }
        List<Demand> demands = dao.queryBuilder().list();
        for (Demand d : demands) {
            KLog.i("d=" + d.toString());
        }
//        Query<Demand> query = dao.queryBuilder().build();
//        List<Demand>  demands = query.list();
//        //下面两个Flag的设置可以在控制台中打印出此次查询的sql语句和value值
//        QueryBuilder.LOG_SQL = true;
//        QueryBuilder.LOG_VALUES = true;
    }

    public void initIntent() {
        persenter = new SplashPersenterImpl(this);
        initRequest();
//        initTestDb();
        int inCount = Integer.valueOf(SPUtil.get(UiSplash.this, "in_count", 0).toString());
        String name = String.valueOf(SPUtil.get(UiSplash.this, "user_name", "").toString());
        String password = String.valueOf(SPUtil.get(UiSplash.this, "password", "").toString());
        if (inCount == 0) {
            //显示引导页
        } else {
            SPUtil.putAndApply(UiSplash.this, "in_count", inCount++);
        }
//        boolean isLogin = Boolean.valueOf(SPUtil.get(UiSplash.this, "is_login", false).toString());
//        if (isLogin) {
//            //直接登录
//            initChat(name, password);
//        } else {
            //跳入登录界面
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(1);
                }
            }, 3000);

//        }

    }

    public void initRequest() {
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String version = packageInfo.versionName;
            tvCode.setText(getResources().getText(R.string.current_version) + version);
            persenter.isRequest();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 防止内存泄露
     */
    private static class SplashHandler extends Handler {
        private final WeakReference<UiSplash> weakReference;

        public SplashHandler(UiSplash uiSplash) {
            weakReference = new WeakReference<UiSplash>(uiSplash);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            UiSplash uiSplash = weakReference.get();
            if (uiSplash != null) {

            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent = new Intent();
            switch (msg.what) {
                case 1:
                    //进入主界面
                    intent.setClass(UiSplash.this, UiMain2.class);
                    startActivity(intent);
                    break;
                case 2:
                    //进入引导页
                    break;
            }

        }
    };

    @Override
    public boolean isRequest() {
        return true;
    }

    @Override
    public void showImage(Bitmap bitmap) {
        if (null != bitmap) {
            ibShow.setImageBitmap(bitmap);
        } else {
            ibShow.setBackgroundResource(R.drawable.ic_favorite_outline_white_24dp);
        }
    }

    /**
     * 初始化环信数据
     *
     * @param name
     * @param password
     */
    protected void initChat(String name, String password) {
        EMChatManager.getInstance().login(name, password, new EMCallBack() {// 回调
            @Override
            public void onSuccess() {
                KLog.i("onSuccess");
//                runOnUiThread(new Runnable() {
//                    public void run() {
                // TODO 保存用户信息
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(2);
                    }
                }, 3000);
                // 加载群组和会话
                EMGroupManager.getInstance().loadAllGroups();
                EMChatManager.getInstance()
                        .loadAllConversations();
                Intent intent = new Intent(UiSplash.this,
                        UiMain2.class);
                startActivity(intent);
                finish();
            }
//                });
//            }

            @Override
            public void onProgress(int progress, String status) {
                KLog.i("onProgress");
            }

            @Override
            public void onError(int code, String message) {
                Log.d("ui_main", "登陆聊天服务器失败！");
                KLog.i("onError");
            }
        });
    }
}


